<template>
  <div class="content" v-loading="submitBtn">
    <div class="scroll-view-box">
      <div class="user-title-box">基础信息</div>
      <el-form label-width="120px" :inline="true" :model="roleInfoform" :rules="roleInfoRules" ref="elForm"
        label-position="top">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="roleInfoform.name" placeholder="请输入角色名称" class="input-width"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="desc">
          <el-input v-model="roleInfoform.desc" type="textarea" placeholder="请输入角色描述(非必填)"
            class="input-width"></el-input>
        </el-form-item>
      </el-form>
      <div class="user-title-box">权限列表</div>
      <div class="permission-list">
        <el-checkbox-group v-model="roleInfoform.checkedList">
          <div class="item-tr" v-for="(item, index) in perList" :key="index">
            <div class="item1-td">{{ item.name }}</div>
            <div class="item2-td">
              <div class="item2-tr" v-for="(item2, index2) in item.nodes" :key="index2">
                <!-- 二级 -->
                <template v-if="!item2.nodes">
                  <div class="item2-td-main">
                    <el-tooltip class="item" effect="dark" :content="item2.name" placement="right">
                      <div class="item2-td-name">
                        <el-checkbox :label="item2.id" @change="checkAll($event, index, index2)">{{ item2.name }}
                        </el-checkbox>
                      </div>
                    </el-tooltip>
                  </div>
                  <div class="item3-td item3-td-width">
                    <div class="item-fun" v-for="(item3, indx3) in item2.operation" :key="indx3">
                      <el-checkbox @change="operChange($event, [index, index2, indx3], '1')" :label="item3.id">{{
                        item3.name }}</el-checkbox>
                    </div>
                  </div>
                </template>
                <!-- 三级 -->
                <template v-else>
                  <div class="item2-td-main">
                    <el-tooltip class="item" effect="dark" :content="item2.name" placement="right">
                      <div class="item2-td-name">
                        <el-checkbox :label="item2.id" @change="checkAll($event, index, index2)">{{ item2.name
                          }}</el-checkbox>
                      </div>
                    </el-tooltip>
                  </div>
                  <div class="tree-box">
                    <div class="item2-tr" v-for="(item3, index3) in item2.nodes" :key="index3">
                      <div class="item2-td-main">
                        <el-tooltip class="item" effect="dark" :content="item3.name" placement="right">
                          <div class="item2-td-name">
                            <el-checkbox :label="item3.id" @change="checkAll($event, index, index2, index3)">{{
                              item3.name }}
                            </el-checkbox>
                          </div>
                        </el-tooltip>
                      </div>
                      <div class="item3-td">
                        <div class="item-fun" v-for="(item3, indx3) in item3.operation" :key="indx3">
                          <el-checkbox @change="operChange($event, [index, index2, index3, indx3], '2')"
                            :label="item3.id">{{
                              item3.name
                            }}</el-checkbox>
                        </div>
                      </div>
                    </div>
                  </div>
                </template>
              </div>
            </div>
          </div>
        </el-checkbox-group>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="saveSubmit('elForm')" :loading="submitBtn">提交</el-button>
        <el-button @click="cancelFunc">关闭</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import permissionApi from "@/api/permissionApi";

export default {
  name: 'role_add',
  data() {
    return {
      editRoleType: 'add',
      // 权限列表数据
      perList: [],
      roleInfoform: {
        id: "",
        name: "",
        desc: "",
        checkedList: [],
      },
      roleInfoRules: {
        name: [{
          required: true,
          message: "请输入角色名称",
          trigger: "change"
        },],
      },
      submitBtn: false,
    };
  },
  computed: {
  },
  mounted() {
    let id = this.$route.query.sn
    if (id) {
      this.editRoleType = "edit";
      permissionApi.getRoleInfo({ id }).then((res) => {
        console.log(res, "getRoleInfo");
        if (res.code == 200) {
          this.roleInfoform.id = id;
          this.roleInfoform.name = res.data.name;
          this.roleInfoform.desc = res.data.desc ? res.data.desc : "";
          this.roleInfoform.checkedList = res.data.checkedList;
        } else {
          this.$message.error(res.message);
        }
      });
    }
    this.getPermissionList();
  },
  methods: {
    // 获取权限列表
    getPermissionList() {
      permissionApi.getPermissionList({
        is_hidden: 1
      }).then((res) => {
        console.log(res, "getPermissionList");
        if (res.code == 200) {
          this.perList = res.data;
        }
      });
    },
    operChange(state, idx_arr, type) {
      let perList = this.perList;
      let checkedList = this.roleInfoform.checkedList
      if (type == '1') {
        let parent_data = perList[idx_arr[0]].nodes[idx_arr[1]]
        if (!checkedList.includes(parent_data.id) && state) {
          this.roleInfoform.checkedList.push(parent_data.id)
        }
      } else {
        // 上级 
        let top_data = perList[idx_arr[0]].nodes[idx_arr[1]]
        let parent_data = perList[idx_arr[0]].nodes[idx_arr[1]].nodes[idx_arr[2]]
        // 上级是否选中，并且子级被选中
        if (!checkedList.includes(top_data.id) && state) {
          this.roleInfoform.checkedList.push(top_data.id)
        }
        if (!checkedList.includes(parent_data.id) && state) {
          this.roleInfoform.checkedList.push(parent_data.id)
        }
      }
    },
    checkAll(state, idx, idx2, idx3) {
      console.log(state, idx, idx2, "state, idx, idx2", idx3)
      let perList = this.perList;
      let data = [];
      if (idx3 != undefined) {
        // 三级
        data = perList[idx].nodes[idx2].nodes[idx3].operation

        // 上级数据
        let checkedList = this.roleInfoform.checkedList
        let parent_data = perList[idx].nodes[idx2]
        // 上级是否选中，并且子级被选中
        if (!checkedList.includes(parent_data.id) && state) {
          this.roleInfoform.checkedList.push(parent_data.id)
        }
        // 获取上级所有的子级id
        let child_id_arr = parent_data.nodes.map(item => item.id)
        // 判断所有子级 是否都不存在选中
        let someValuesIncluded = child_id_arr.some(value => checkedList.includes(value));
        // 都没选中 父级去掉选中
        if (!state && !someValuesIncluded) {
          let idx = checkedList.indexOf(parent_data.id)
          if (idx !== -1) {
            this.roleInfoform.checkedList.splice(idx, 1);
          }
        }

        console.log(perList[idx].nodes[idx2], 'zxxcasdasdasd')
      } else {
        // 二级
        if (perList[idx].nodes[idx2].nodes) {
          console.log(perList[idx].nodes[idx2].nodes);
          perList[idx].nodes[idx2].nodes.forEach((item) => {
            data.push(item);
            if (item.operation.length) {
              item.operation.forEach((child) => {
                data.push(child);
              });
            }
          });
        } else {
          data = perList[idx].nodes[idx2].operation;
        }
      }
      if (state) {
        this.setChecked(data);
      } else {
        this.setUnChecked(data);
      }
    },
    // 设置全不选
    setUnChecked(data) {
      let checkedList = this.roleInfoform.checkedList;
      data.forEach((item) => {
        if (checkedList.includes(item.id)) {
          var index = checkedList.indexOf(item.id);
          checkedList.splice(index, 1);
        }
      });
    },
    // 设置全选
    setChecked(data) {
      let checkedList = this.roleInfoform.checkedList;
      data.forEach((item) => {
        if (!checkedList.includes(item.id)) {
          checkedList.push(item.id);
        }
      });
    },
    // 修改perList数组变成一维
    setArrayFormat() {
      let perList = this.perList;
      let arr = [];
      perList.forEach((item) => {
        item.nodes.forEach((item2) => {
          var obj = {};
          obj.id = item2.id;
          obj.pid = item2.parent_id;
          arr.push(obj);
          if (item2.nodes) {
            item2.nodes.forEach((item3) => {
              var obj = {};
              obj.id = item3.id;
              obj.pid = item3.parent_id;
              arr.push(obj);
              item3.operation.forEach((item4) => {
                var obj = {};
                obj.id = item4.id;
                obj.pid = item4.parent_id;
                arr.push(obj);
              });
            });
          }
          item2.operation.forEach((item3) => {
            var obj = {};
            obj.id = item3.id;
            obj.pid = item3.parent_id;
            arr.push(obj);
          });
        });
      });
      return arr;
    },
    // 提交
    saveSubmit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let roleInfoform = this.roleInfoform;
          // 选中的处理格式
          let checkedList = roleInfoform.checkedList;
          console.log(checkedList, "选中权限")
          if (checkedList.length < 1) {
            this.$message({
              message: "请选择至少一个权限",
              type: "warning",
            });
            return;
          }
          this.submitBtn = true;
          let perList = this.setArrayFormat();
          let checked_arr = [];

          perList.forEach((item) => {
            if (checkedList.includes(item.id)) {
              checked_arr.push(item);
            }
          });
          if (this.editRoleType == "add") {
            this.setRoleAdd(roleInfoform, checked_arr);
          } else {
            this.setRoleSave(roleInfoform, checked_arr);
          }
        } else {
          this.$message.warning('有必填未填写，无法提交！')
          return false;
        }
      });
    },
    setRoleAdd(roleInfoform, checked_arr) {
      permissionApi
        .setRoleAdd({
          name: roleInfoform.name,
          desc: roleInfoform.desc,
          checked_arr: JSON.stringify(checked_arr),
        })
        .then((res) => {
          console.log(res, "setRoleAdd");
          if (res.code == 200) {
            this.$message({
              message: "添加成功",
              type: "success",
            });
            this.cancelFunc()
          } else {
            this.$message.error(res.message);
          }
          this.submitBtn = false;
        });
    },
    setRoleSave(roleInfoform, checked_arr) {
      permissionApi
        .setRoleSave({
          id: roleInfoform.id,
          name: roleInfoform.name,
          desc: roleInfoform.desc,
          checked_arr: JSON.stringify(checked_arr),
        })
        .then((res) => {
          console.log(res, "setRoleAdd");
          if (res.code == 200) {
            this.$message({
              message: "修改成功",
              type: "success",
            });
            this.cancelFunc()
          } else {
            this.$message.error(res.message);
          }
          this.submitBtn = false;
        });
    },
    // 关闭
    cancelFunc() {
      this.$goBackTab(this);
    },

  },
};
</script>
<style lang="scss" scoped>
@import "index.scss";
@import "@/styles/addPage.scss";
</style>